using System.Xml;
using System.Collections.Generic;

namespace RealDolmen.SharePoint.ListFeatures.Elements
{
    public class ListFeatureElements
    {
        List<ListFeatureElement> elements;
        ListFeatureDefinition featureDefinition;

        public ListFeatureElements(ListFeatureDefinition featureDefinition)
        {
            elements = new List<ListFeatureElement>();
            this.featureDefinition = featureDefinition;
        }

        public ListFeatureElement AddFromXml(XmlNode xnElementDefinition, ListFeatureElementsFile file)
        {
            ListFeatureElement item = ListFeatureElement.CreateAppropriateElementType(xnElementDefinition, featureDefinition, file);
            if (item != null)
            {
                this.elements.Add(item);
            }
            return item;
        }

        public ListFeatureElement AddFromFeature(XmlNode node, ListFeatureElementsFile file, ListFeature listFeature)
        {
            ListFeatureElement item = ListFeatureElement.CreateAppropriateElementType(node, featureDefinition, file, listFeature);
            if (item != null)
            {
                this.elements.Add(item);
            }
            return item;
        }

        public void Provision(ListFeature listFeature)
        {
            foreach (ListFeatureElement element in elements)
            {
                element.Activate(listFeature);
            }

        }
        public void Unprovision(ListFeature listFeature)
        {
            foreach (ListFeatureElement element in elements)
            {
                element.Deactivate(listFeature);
            }
        }

        public List<ListFeatureElement> Get()
        {
            return elements;
        }

        public List<T> Get<T>() where T : ListFeatureElement
        {
            List<T> list = new List<T>();

            foreach (ListFeatureElement element in elements)
            {
                if (element is T)
                    list.Add(element as T);
            }
            return list;
        }

        public T Get<T>(T toLookFor) where T : ListFeatureElement
        {
            foreach (ListFeatureElement element in elements)
            {
                if (element is T && element.Key == toLookFor.Key)
                    return element as T;
            }
            return null;
        }
    }
}
